﻿package main

import (
	"fmt"
	"math/rand"
	"simudata/protocol"
	"strconv"
	"time"

	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/spf13/viper"
	"google.golang.org/protobuf/proto"
)

// 生成随机的浮点数，范围在minValue~maxValue区间
// minValue:最小浮点数
// maxValue:最大浮点数
func randomFloat64(minValue float64, maxValue float64, percision int) float64 {
	value := rand.Float64()*(float64(maxValue)-float64(minValue)) + float64(minValue)
	value, _ = strconv.ParseFloat(strconv.FormatFloat(value, 'f', percision, 64), 64)
	return value
}

// 生成随机字符串
func randomString(n int) string {
	var letters = []byte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
	result := make([]byte, n)
	for i := range result {
		result[i] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}

// 模拟生成采集器数据
// name: 采集器名称
// num: 传感器数量
// sampleSize: 每个传感器的采样数
// intervalDuration: 采样的间隔时间单位毫秒
// minValue: 随机数的最小值范围
// maxValue: 随机数的最大值范围
func generateSensorDatas(timeStamp int64, name string, num int, sampleSize int64, intervalDuration int64, minValue float64, maxValue float64) *protocol.SimuMessage {
	percision := viper.GetInt(floatPercisionKey)
	var message protocol.SimuMessage
	message.Name = name
	timeOffset := intervalDuration / int64(sampleSize)
	for j := int64(0); j < sampleSize; j++ {
		sampleTimeStamp := timeStamp + int64(j)*timeOffset
		for i := 0; i < num; i++ {
			var data protocol.SimuData
			data.Timestamp = sampleTimeStamp
			data.Id = int32(i)
			data.Value = randomFloat64(minValue, maxValue, percision)
			message.Datas = append(message.Datas, &data)
		}
	}

	return &message
}

var timeOffset int32

func onMessageHandler(c mqtt.Client, m mqtt.Message) {
	timeStamp := time.Now().UnixMilli()
	var simuMessage protocol.SimuMessage
	err := proto.Unmarshal(m.Payload(), &simuMessage)
	if nil == err {
		offset := int32(timeStamp) - int32(simuMessage.Datas[0].Timestamp)
		if offset != timeOffset {
			fmt.Println("消息延迟毫秒:", offset)
			timeOffset = offset
		}
	}
}
